package main

import (
	"context"
	"fmt"
	"time"

	"atomgit.com/openlinksaas/proto-gen-go.git/net_proxy_api"
)

func sendData(tunnelId, connId string, data []byte, client net_proxy_api.NetProxyApiClient) error {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	res, err := client.WriteConn(ctx, &net_proxy_api.WriteConnRequest{
		TunnelId: tunnelId,
		ConnId:   connId,
		Data:     data,
	})
	if err != nil {
		return err
	}
	if res.Code != net_proxy_api.WriteConnResponse_CODE_OK {
		return fmt.Errorf(res.ErrMsg)
	}
	return nil
}

func recvData(tunnelId, connId string, client net_proxy_api.NetProxyApiClient) ([]byte, error) {
	ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
	defer cancel()

	res, err := client.ReadConn(ctx, &net_proxy_api.ReadConnRequest{
		TunnelId: tunnelId,
		ConnId:   connId,
	})
	if err != nil {
		return nil, err
	}
	if res.Code != net_proxy_api.ReadConnResponse_CODE_OK {
		return nil, fmt.Errorf(res.ErrMsg)
	}
	return res.Data, nil
}

func keepAlive(tunnelId string, client net_proxy_api.NetProxyApiClient) error {
	ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
	defer cancel()

	res, err := client.KeepTunnelAlive(ctx, &net_proxy_api.KeepTunnelAliveRequest{
		TunnelId: tunnelId,
	})
	if err != nil {
		return err
	}
	if res.Code != net_proxy_api.KeepTunnelAliveResponse_CODE_OK {
		return fmt.Errorf(res.ErrMsg)
	}
	return nil
}
